<template>
  <el-card class="box-card">
    <el-button :icon="Plus" type="primary" @click="addTrademark">
      添加品牌
    </el-button>
    <el-table :data="records" style="width: 100%; margin-top: 10px" border>
      <el-table-column label="序号" type="index" align="center " width="100" />
      <el-table-column align="center " clabel="品牌名称" prop="tmName" />
      <el-table-column align="center " label="品牌logo" prop="logoUrl">
        <template v-slot="{ row }">
          <img :src="row.logoUrl" style="width: 90px; height: 90px" />
        </template>
      </el-table-column>
      <el-table-column align="center " label="品牌操作">
        <template v-slot="{ row }">
          <el-button type="primary" :icon="Edit" @click="edit(row)" />
          <el-popconfirm
            :title="`是否删除-${row.tmName}?`"
            width="266px"
            icon="CircleCloseFilled"
            icon-color="#229241"
            @confirm="confirmone(row.id)"
          >
            <template #reference>
              <el-button type="danger" :icon="Delete" />
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <!-- v-model:current-page="currentPage3" 当前的页面
       v-model:page-size="pageSize3" 一页显示多少数据
       page-size 快速选择的当前的页数
       small  小型分页
     -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="getdata"
      pager-count="5"
      v-model:current-page="page"
      v-model:page-size="limit"
      :page-sizes="[3, 5, 7, 9]"
      :background="true"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total"
    />
    <!-- 对话框 -->
    <el-dialog
      v-model="centerDialogVisible"
      :title="ruleForm.id ? '编辑品牌' : '添加品牌'"
      center
      :before-close="cancellation"
    >
      <span>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
        >
          <el-form-item label="品牌名称" prop="tmName" style="width: 80%">
            <el-input v-model="ruleForm.tmName" />
          </el-form-item>
          <el-form-item label="品牌LOGO" prop="logoUrl" style="width: 80%">
            <!-- 这里注意action 这个字段api字段 （数据反向代理） -->
            <el-upload
              ref="upload"
              style="width: 100%"
              drag
              action="/api/admin/product/fileUpload"
              multiple
              :before-upload="beforeAvatarUpload"
              :on-success="handleAvatarSuccess"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                将文件放在此处
                <em>点击上传</em>
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
      </span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancellation">取消</el-button>
          <el-button type="primary" @click="determine">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from "vue"
import { Plus, Edit, Delete, UploadFilled } from "@element-plus/icons-vue"
import {
  brandapproach,
  AddModifications,
  Deletebrand,
} from "@/api/commodity/brand/index.ts"
import type {
  Brandingtow,
  Addtypenot,
  rowtype,
  Brandingone,
} from "@/api/commodity/brand/type"
import type { UploadProps } from "element-plus"
import { ElMessage } from "element-plus"
let page = ref<number>(1)
let limit = ref<number>(3)
let total = ref<number>(0)
let records = ref<Brandingtow>([])
const ruleForm = reactive<Brandingone>({
  tmName: "",
  logoUrl: "",
})
const upload = ref() //ref 获取组件实例
const ruleFormRef = ref() //获取组件实例弹出层
//品牌自定义校验规则方法
const validatorTmName = (rule: any, value: any, callBack: any) => {
  //是当表单元素触发blur时候,会触发此方法
  //自定义校验规则
  if (value.trim().length >= 2) {
    callBack()
  } else {
    //校验未通过返回的错误的提示信息
    callBack(new Error("品牌名称位数大于等于两位"))
  }
}
// 上传自定义校验规则方法
const Uploadverification = (rule: any, value: any, callBack: any) => {
  if (value.length != "") {
    callBack()
  } else {
    callBack(new Error("请上传品牌图片"))
  }
}
// 自定义校验规则
const rules = reactive<any>({
  tmName: [{ required: true, trigger: "blur", validator: validatorTmName }],
  logoUrl: [{ required: true, validator: Uploadverification }],
})
// 对话宽开关
const centerDialogVisible = ref<boolean>(false)
const getdata = async () => {
  const data: any = await brandapproach(page.value, limit.value)
  if (data.code === 200) {
    total.value = data.data.total
    // console.log(data.data.records, 13);
    records.value = data.data.records
  }
}
// 页面开始挂载完毕 就获取数据
onMounted(() => {
  getdata()
})
//  分页
const handleSizeChange = () => {
  // 右边改变一页展示多少条数据发生变化回到第一页
  page.value = 1
  getdata()
}
// 添加 清空表单里面的字段
const addTrademark = () => {
  centerDialogVisible.value = true
  ruleForm.id = 0
  ruleForm.tmName = ""
  ruleForm.logoUrl = ""

  // 清空上传的文件
  if (ruleForm.logoUrl === "") {
    upload.value.clearFiles()
  }
}
// 编辑
const edit = (row: rowtype) => {
  centerDialogVisible.value = true
  ruleForm.tmName = row.tmName
  ruleForm.id = row.id //ruleForm这个对象里面添加一个id属性
  ruleForm.logoUrl = row.logoUrl
  // console.log(row, "这是什么");
}
// 确定添加数据给后台的确定按钮
const determine = async () => {
  await ruleFormRef.value.validate() //校验通过返回true 不通过 不返回接口
  centerDialogVisible.value = false
  const data: Addtypenot = await AddModifications(ruleForm)
  if (data.code === 200) {
    ElMessage({
      type: "success",
      message: ruleForm.id ? "编辑品牌成功" : "添加品牌成功",
    })
    centerDialogVisible.value = false
  } else {
    ElMessage({
      type: "error",
      message: ruleForm.id ? "编辑品牌失败" : "添加品牌失败",
    })
  }
  getdata(ruleForm.id ? page.value : 1)
}
// 图片上传之前触发 可以限制上传的类型大小  console.log(rawFile, '上传前执行');
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  // 业务要求 图片格式 png jpg gif 大小只能等于4百兆
  if (
    rawFile.type === "image/png" ||
    rawFile.type === "image/jpeg" ||
    rawFile.type === "image/gif"
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage.error("只能文件不能大于4mb")
      return false
    }
  } else {
    ElMessage.error("只能上传图片位置 png jpg gif格式的图片")
    return false
  }
}
// 上传成功的钩子
const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  //console.log(response.data, '上传成功的钩子方法');//上传成功返回的接口数据
  // console.log(uploadFile, '上传成功的钩子方法1');
  ruleForm.logoUrl = response.data
  ruleFormRef.value.clearValidate("logoUrl") //清除表单上传文件的字段校验信息
}
// 取消
const cancellation = () => {
  // ruleFormRef.value.resetFields()//清空表格里面的内容
  ruleFormRef.value.clearValidate("tmName")
  ruleFormRef.value.clearValidate("logoUrl")
  centerDialogVisible.value = false
}
// 删除
const confirmone = async (id: number) => {
  const res: any = await Deletebrand(id)
  getdata()
  ElMessage({
    message: res.data ? res.data : `删除-${res.message}`,
    type: res.data ? "error" : "success",
  })
}
</script>

<style scoped></style>
